﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace T02TcpServer
{
    class ClientThread
    {
        //保存客户端的连接个数
        public static int Connections = 0;
        public Socket service;
        public ClientThread(Socket socket)
        {
            this.service = socket;
        }
        //处理服务端与客户端之间的数据
        public void HandData()
        {
            //数据传输
            //1)传输的数据类型：二进制数据和文本数据
            //2)传输的数据协议：二进制类协议（图片、音频、视频）  文本类（JSON、XML、字符串）
            string data = null;
            //数据缓冲池
            byte[] buff = new byte[1024];
            //连接客户端的统计值加1
            if (service != null)
            {
                Connections++; 
            }
            Console.WriteLine($"新客户端连接:{Connections}个连接");
            int i = 0;
            while((i=service.Receive(buff))!=0)
            {
                data = Encoding.ASCII.GetString(buff,0,i);
                data=data.ToUpper();
                byte[] buf = new byte[1024];
                buf = Encoding.ASCII.GetBytes(data); 
                Console.WriteLine($"发送数据：{data}");
                //发送应答数据
                service.Send(buf);
            }
            Connections--;
            Console.WriteLine($"客户端连接关闭:{Connections}个连接");
            service.Close();
        }
    }
}
